local skynet = require "skynet"
local mng = require "cached.mng"
local user = require "cached.user"
local item = require "cached.item"
local logger = require "logger"
require "skynet.manager"

local CMD = {}

function CMD.run(func_name, mod, sub_mod, id, ...)
    local func = mng.get_func(mod, sub_mod, func_name)
    local cache = mng.load_cache(mod, sub_mod, id)
    return func(id, cache, ...)
end 

function CMD.SIGHUP()
    logger.info(SERVICE_NAME, "SIGHUP to save db. Doing.")
    mng.do_save_loop()
    logger.info(SERVICE_NAME, "SIGHUP to save db. Down.")
end

function CMD.monitor_lru()
    mng.monitor_cache_list()
end

-- 服务启动做一次数据库的默认配置操作
function mongodb_do_once()
    local mongo = require "skynet.db.mongo"
    local mongo_host = skynet.getenv("mongodb_ip") or "localhost"
    local mongo_port = skynet.getenv("mongodb_port") or 27017
    local mongo_user = skynet.getenv("mongodb_user") or "cauchy"
    local mongo_pwd = skynet.getenv("mongodb_pwd") or "root"
    local mongo_game = skynet.getenv("mongodb_db_name") or "game"
    local mongo_cache = skynet.getenv("cache_db_name") or "cache"
    local c = mongo.client({
        host = mongo_host,
        port = mongo_port,
    })
    local adminDB = c:getDB("admin")
    adminDB:runCommand("createUser", "root", "pwd", "root", "roles", '{role: "root"}')
    adminDB:auth("root", "root")
    local gameDB = c:getDB(mongo_game)
    gameDB:runCommand("createUser", mongo_user, "pwd", mongo_pwd, "roles", '[{role: "readWrite", db: mongo_game}]')
    local cacheDB = c:getDB(mongo_cache)
    cacheDB:runCommand("createUser", mongo_user, "pwd", mongo_pwd, "roles", '[{role: "readWrite", db: mongo_cache}]')

    c:disconnect()
end

skynet.start(function()
    skynet.dispatch("lua", function(_, _, cmd, ...)
        local f = assert(CMD[cmd])
        skynet.ret(skynet.pack(f(...)))
    end)

    skynet.register(".cached")
    mongodb_do_once()

    mng.init()
    user.init()
    item.init()
end)